package com.leetcode.partition3;

/**
 * @author `RKC`
 * @date 2021/8/6 8:32
 */
public class LC231二的幂 {

    public static boolean isPowerOfTwo(int n) {
        return bitManipulation(n);
    }

    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(8));
    }

    //位运算：对于一个是2的幂的正整数n，有n & n-1 === 0
    public static boolean bitManipulation(int n) {
        if (n < 1) return false;
        return (n & n - 1) == 0;
    }

    //二分法
    public static boolean dichotomy(int n) {
        if (n < 1) return false;
        if (n == 1) return true;
        int start = 1, end = n;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            int res = (int) Math.pow(2, mid);
            if (res == n) return true;
            else if (res < n) start = mid + 1;
            else end = mid - 1;
        }
        return false;
    }
}
